import React, { useState } from "react";

type TodoInputProps = {
  onAdd: (newTodo: string) => void;
};

const TodoInput: React.FC<TodoInputProps> = ({ onAdd }) => {
  const [inputValue, setInputValue] = useState<string>("");

  const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setInputValue(event.target.value);
  };

  const handleAddTodo = (event: React.FormEvent<HTMLButtonElement>) => {
    event.preventDefault(); // 阻止表单默认提交行为
    if (inputValue.trim()) {
      // 如果输入值不为空
      onAdd(inputValue); // 调用传入的 onAdd 函数，添加待办事项
      setInputValue(""); // 清空输入框
    }
  };

  return (
    <form onSubmit={handleAddTodo}>
      <input
        type="text"
        value={inputValue}
        onChange={handleInputChange}
        placeholder="Add a new todo..."
      />
      <button type="submit">Add Todo</button>
    </form>
  );
};

export default TodoInput;
